<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item title="论文信息" :content="isSubmit('thesisId')">
      </t-step-item>
      <t-step-item title="论文人员" :content="isSubmit('memberId')">
      </t-step-item>
      <t-step-item title="论文项目来源" :content="isSubmit('projectId')">
      </t-step-item>
      <t-step-item title="附件信息" :content="isSubmit('fileId')">
      </t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div class="apply-form">
      <t-form ref="form" :key="activeForm" colon v-if="activeForm === 0" class="step-form" :data="formData0" :rules="rules0"
              labelWidth="120px">
        <t-row style="flex: 1">
          <t-col :span="12">
            <t-row style="row-gap:24px">
              <t-col :span="12">
                <t-form-item label="论文名称" name="name">
                  <t-input clearable v-model="formData0.name" placeholder="请输入内容"></t-input>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item label="刊号(ISSN)" name="issn">
                  <t-input  clearable style="width:390px" v-model="formData0.issn" placeholder="请输入内容"></t-input>
                </t-form-item>
              </t-col>
  <!--            <t-col :span="6">-->
  <!--              <t-form-item label="主办单位" name="hostDept">-->
  <!--                <t-input clearable style="width:390px" v-model="formData0.hostDept" placeholder="请输入内容"></t-input>-->
  <!--              </t-form-item>-->
  <!--            </t-col>-->
              <t-col :span="6">
                <t-form-item label="刊物名称" name="publicationName">
                  <t-select  style="width:390px" creatable clearable @change="onPublicationNameChange"  @create="createPublicationNameOptions" filterable v-model="formData0.publicationName" :options="periodicalOptions">
                  </t-select>
  <!--                <t-input style="width:390px" v-model="formData0.publicationName" placeholder="请输入内容"></t-input>-->
                </t-form-item>
              </t-col>
  <!--            <t-col :span="6">-->
  <!--              <t-form-item label="个人排名" name="thesisRanking">-->
  <!--                <t-select style="width:390px" clearable filterable v-model="formData0.thesisRanking" :options="dict.type.thesis_ranking">-->
  <!--                </t-select>-->
  <!--              </t-form-item>-->
  <!--            </t-col>-->
              <t-col :span="6">
                <t-form-item label="出版年月" name="publishDate">
                  <t-date-picker style="width:390px" clearable v-model="formData0.publishDate"></t-date-picker>
                </t-form-item>
              </t-col>
  <!--            <t-col :span="6">-->
  <!--              <t-form-item label="完成字数" name="completeWordCount">-->
  <!--                <t-input-adornment append="千字">-->
  <!--                  <t-input-number placeholder="请输入至多三位整数"  :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"-->
  <!--                                  v-model="formData0.completeWordCount"-->
  <!--                                  theme="normal"-->
  <!--                                  :min="0"></t-input-number>-->
  <!--                </t-input-adornment>-->
  <!--              </t-form-item>-->
  <!--            </t-col>-->
              <t-col :span="6">
                <t-form-item label="级别" name="paperLevel">
                  <t-select style="width:390px" clearable filterable v-model="formData0.paperLevel" :options="dict.type.paper_level">
                  </t-select>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item label="检索验证地址" name="verifyAddress">
                  <t-textarea
                    clearable :autosize="{minRows: 3}"
                    v-model="formData0.verifyAddress"
                    placeholder="请输入"
                    style="width:390px"
                  />
  <!--                <t-input clearable style="width:390px" v-model="formData0.verifyAddress" placeholder="请输入内容"></t-input>-->
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item help="手输支持自定义创建" label="关键词" name="keyWordList">
                  <t-select
                    v-model="formData0.keyWordList"
                    creatable
                    filterable
                    multiple
                    placeholder="手输支持自定义创建"
                    :options="dict.type.cg_key_word"
                    style="width: 390px;"
                    @create="createKeyWordOptions"
                  >
                  </t-select>
                </t-form-item>
              </t-col>
              <t-col :span="12">
                <t-form-item label="摘要" name="digest">
                  <t-textarea
                    clearable :autosize="{minRows: 5}"
                    v-model="formData0.digest"
                    placeholder="请输入"
                  />
                </t-form-item>
              </t-col>
  <!--            <t-col :span="12">-->
  <!--              <t-form-item label="备注" name="note">-->
  <!--                <t-textarea-->
  <!--                  clearable :autosize="{minRows: 5}"-->
  <!--                  v-model="formData0.note"-->
  <!--                  placeholder="明确标明符合申报条件的具体条款"-->
  <!--                />-->
  <!--              </t-form-item>-->
  <!--            </t-col>-->
            </t-row>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="11" >
          </t-col>
          <t-col :span="1" >
            <t-button theme="primary" @click="onSubmit0()">下一步</t-button>
          </t-col>
          <!-- <t-col :span="1" class="operation-container">
            <t-button variant="outline" @click="close">返回</t-button>
          </t-col> -->
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 1" label-align="top" class="step-form" :data="formData1"
              :rules="rules1"
              labelWidth="120px">
        <t-row style="flex: 1">
          <t-form-item :show-error-message="false" name="memberList" label="必填">
            <thesis-member :objId="objId" v-model="formData1.memberList" :editOpen="true"></thesis-member>
          </t-form-item>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-button  @click="onCurChanged(0)" theme="primary" variant="base">上一步
            </t-button>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button theme="primary" @click="onSubmit1()">下一步</t-button>
          </t-col>
          <!-- <t-col :span="1" class="operation-container">
            <t-button variant="outline" @click="close">返回</t-button>
          </t-col> -->
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 2" class="step-form" :data="formData2" :rules="rules2"
              labelWidth="120px">
        <t-row style="flex: 1">
          <t-alert style="margin-bottom: 14px;width: 100%" theme="info" title="说明">
            <div slot="message">
              <p class="span-txt">
                内部项目当前系统申报的项目(非必填)
              </p>
              <p class="span-txt">
                外部项目未在当前系统申报的项目(非必填)
              </p>
            </div>
          </t-alert>
          <t-form-item :show-error-message="false" name="projectList">
            <thesis-project  :objId="objId" ref="thesis-project" :applyData="formData2.applyData" v-model="formData2.projectList"
                            :editOpen="true"></thesis-project>
          </t-form-item>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-button  @click="onCurChanged(1)" theme="primary" variant="base">上一步
            </t-button>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button theme="primary" @click="onSubmit2()">下一步</t-button>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 3" class="step-form" :data="formData3" :rules="rules3"
              labelWidth="120px">
        <t-row style="flex: 1">
          <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{row, rowIndex}">
              {{ rowIndex+1 }}
            </template>
            <template #op="{row}">
              <file-upload tips="限制pdf、图片" accept="application/pdf,image/*" v-model="row.fileIds"
                           :moduleKey="row.moduleKey"
                           :fileList="row.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-button  @click="onCurChanged(2)" theme="primary" variant="base">上一步
            </t-button>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-tooltip content="提交后仍可以修改">
              <t-button :disabled="isCommit" theme="primary" @click="onSubmit3(2)">提交</t-button>
            </t-tooltip>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import ThesisMember from "./components/thesis-member.vue";
import ThesisProject from "./components/thesis-project.vue";
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "thesis-apply",
  dicts: ["paper_level","thesis_ranking", "cg_key_word"],
  components: {
    ThesisMember,
    ThesisProject,
    FileUpload
  },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        // {
        //   id: 1,
        //   c1: "期刊封面",
        //   c2: "是",
        //   moduleKey: "thesisQKFM",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
        // {
        //   id: 2,
        //   c1: "期刊目录",
        //   c2: "是",
        //   moduleKey: "thesisQKML",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
        // {
        //   id: 3,
        //   c1: "期刊版权页,检索证明",
        //   c2: "是",
        //   moduleKey: "thesisQKBQY",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
        {
          id: 1,
          c1: "正文",
          c2: "是",
          moduleKey: "thesisZW",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "其他",
          c2: "否",
          moduleKey: "cgzhlwqt",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },
        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      objId: null,
      taskId: null,
      applyLoading: false,
      isCommit: false,
      activeForm: 0,
      formData0: {
        digest: '',
        name: null,
        issn: '',
        hostDept: '',
        publicationName: '',
        thesisRanking: '',
        publishDate: '',
        completeWordCount: null,
        paperLevel: '',
        keyWord: '',
        keyWordList: [],
        note: '',
        verifyAddress: ''
      },
      rules0: {
        name: [
          {required: true, message: "论文名称不能为空"}
        ],
        digest: [
          {required: true, message: "摘要不能为空"}
        ],
        keyWordList: [{required: true, validator: (val) => val && val.length, message: "关键词不能为空", type: "error"}],
        issn: [
          {required: true, message: "刊号(ISSN)不能为空"}
        ],
        hostDept: [
          {required: true, message: "主办单位不能为空"}
        ],
        publicationName: [
          {required: true, message: "刊物名称不能为空"}
        ],
        thesisRanking: [
          {required: true, message: "个人排名不能为空"}
        ],
        publishDate: [
          {required: true, message: "出版年月不能为空"}
        ],
        completeWordCount: [
          {required: true, message: "完成字数不能为空"},
          {
            validator: (val) => val<1000, message: "完成字数至多三位整数", type: "error"
          },
        ],
        paperLevel: [
          {required: true, message: "级别不能为空"},
        ],
        note: [
          {required: true, message: "备注(明确标明符合申报条件的具体条款)不能为空"},
        ],
        verifyAddress:[
          {required: true, message: "检索验证地址不能为空"},
        ]
      },
      formData1: {
        memberList: []
      },
      rules1: {
        memberList: [
          {required: true, validator: (val) => val && val.length, message: "论文人员不能为空", type: "error"}
        ]
      },
      formData2: {
        projectList: [],
        applyData: []
      },
      rules2: {},
      formData3: {},
      rules3: {},
      periodicalOptions: []
    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler(val) {
        const targetEle = document.getElementById("main")
        if (targetEle) {
          const {pos, top} = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({behavior: 'smooth', block: 'start', inline: "nearest"});
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      }
    }
  },
  created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少id");
      return false;
    }
    this.taskId = taskId;
    this.objId = sessionStorage.getItem(`${this.taskId}-thesis-thesisId`);
    const activeForm = Number(sessionStorage.getItem(`${this.taskId}-thesis-activeForm`)) || 0;
    this.onCurChanged(activeForm, 0);
    this.getPeriodicalList();
  },
  methods: {
    onPublicationNameChange(val,content){
      if(content.option.paperLevel){
        this.formData0.paperLevel = content.option.paperLevel;
      }
    },
    createPublicationNameOptions(value){
      this.periodicalOptions.push({
        label:`${value}`,
        value,
        name: value
      });
    },
    getPeriodicalList(){
      this.$api.cgzh.thesisPeriodical.list({
        pageNum: 1,
        pageSize: 100000,
      }).then(response => {
        this.periodicalOptions = response.rows.map(val=>({value:val.name,label:val.name,paperLevel:val.paperLevel}));
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onCurChanged(cur, pre) {
      if (Number(cur) !== 0) {
        if (!sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)) {
          this.applyLoading = false;
          this.$message.error("论文信息还未提交")
          return false;
        }
      }
      this.applyLoading = true;
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)) {
          const thesisId = Number(sessionStorage.getItem(`${this.taskId}-thesis-thesisId`));
          this.$api.cgzh.thesis.get(thesisId).then(response => {
            if (response.data) {
              this.formData0.keyWordList = response.data.keyWord?.split(",").filter(item=> item !== '')
              Object.assign(this.formData0, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 1) {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
        this.applyLoading = false;
      } else if (Number(cur) === 2) {
        // 通过子系统跳转过来录入
        const { serviceCode, serviceId, serviceName, businessId,businessName } = this.$route.query;
        if(businessId){
          this.formData2.applyData = [
            {
              id: Date.parse(new Date()),
              thesisId: this.objId,
              serviceId: Number(serviceId),
              serviceName,
              serviceCode,
              businessId: Number(businessId),
              businessName,
              isInnerProject: '1',
              projectOptions: [
                {
                  businessId: Number(businessId),
                  businessName,
                }
              ]
            }
          ]
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
          this.applyLoading = false;
        }else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 3) {
        getFiles(sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)).then((res) => {
          if (res.data.length > 0) {
            sessionStorage.setItem(`${this.taskId}-thesis-fileId`, res.data.length)
          }
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val,index)=>{
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-thesis-activeForm`, cur);
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        this.applyLoading = false;
      }
    },
    isSubmit(name) {
      if (sessionStorage.getItem(`${this.taskId}-thesis-${name}`)) {
        return '已提交'
      }
      return '未提交';
    },
    isSubmitStatus(name) {
      return !!sessionStorage.getItem(`${this.taskId}-thesis-${name}`);
    },
    onSubmit0() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          this.formData0.keyWord = this.formData0.keyWordList.join(",");
          if (!sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)) {
            this.$api.cgzh.thesis.add({
              ...this.formData0,
            }).then(response => {
              this.objId = response.data.id;
              sessionStorage.setItem(`${this.taskId}-thesis-thesisId`, response.data.id)
              this.$message.success('提交成功');
              this.onCurChanged(1)
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.cgzh.thesis.update({
              ...this.formData0,
              id: sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)
            }).then(response => {
              this.$message.success('提交成功');
              this.onCurChanged(1)
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit1() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          this.$api.cgzh.thesis.memberAddList(this.formData1.memberList).then(response => {
            sessionStorage.setItem(`${this.taskId}-thesis-memberId`, this.formData1.memberList.length)
            this.$message.success('提交成功');
            this.onCurChanged(2)
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit2() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs["thesis-project"].checkData()
          if (!isValidate) {
            return false;
          }
          this.applyLoading = true;
          this.$api.cgzh.thesis.projectAddList(this.formData2.projectList).then(response => {
            sessionStorage.setItem(`${this.taskId}-thesis-projectId`, this.formData2.projectList.length)
            this.$message.success('提交成功');
            this.onCurChanged(3)
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit3(type) {
      if(type===1){
        this.applyLoading = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val=>{
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.cgzh.thesis.update({
          id: sessionStorage.getItem(`${this.taskId}-thesis-thesisId`),
          sysAttMainVo: {
            sysAttMainIds,
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('暂存成功');
          this.applyLoading = false;
          // this.close();
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      }else {
        const isValidate = this.projectFileData.every(val=>{
          if(val.require && val.fileIds.length <= 0){
            this.$message.error(`需要上传${val.c1}`);
            return false;
          }
          return true
        })
        if(!isValidate){
          return false
        }
        if (!sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)) {
          this.$message.error("论文信息还未提交")
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-thesis-memberId`)) {
          this.$message.error("论文人员还未提交");
          this.applyLoading = false;
          return false;
        }
        this.applyLoading = true;
        this.isCommit = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val=>{
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.cgzh.thesis.submit({
          id: Number(sessionStorage.getItem(`${this.taskId}-thesis-thesisId`)),
          sysAttMainVo: {
            sysAttMainIds
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('提交成功');
          this.applyLoading = false;
          this.isCommit = false;
          this.close();
        }).catch((e) => {
          this.applyLoading = false;
          this.isCommit = false;
          this.$message.error(e.toString());
        });
      }
    },
    createKeyWordOptions(value){
      this.dict.type.cg_key_word.push({
        label:`${value}`,
        value,
      });
    },
    close() {
      this.applyLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({path: "/cgzh/thesis/thesis-my"});
      }, 1000)
    },
  }
}
</script>

<style lang="less" scoped>
.base-container {
  display: flex;
  flex-direction: column;
}

.step-form {
  padding: 0 24px;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
